const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const mongoose = require('mongoose');
const path = require('path');

// 初始化Express应用
const app = express();
// 创建HTTP服务器
const server = http.createServer(app);
// 创建WebSocket服务器
const wss = new WebSocket.Server({ server });

// 连接MongoDB数据库
mongoose.connect('mongodb://localhost:27017/ctrl100panel', {
  useNewUrlParser: true,
  useUnifiedTopology: true
})
.then(() => console.log('MongoDB connected'))
.catch(err => console.error('MongoDB connection error:', err));

// 解析JSON请求体
app.use(express.json());

// 简单的HTTP路由
app.get('/', (req, res) => {
  res.send('Backend server is running');
});

// WebSocket连接处理
wss.on('connection', (ws) => {
  console.log('New WebSocket connection');

  // 发送欢迎消息
  ws.send(JSON.stringify({
    type: 'connection',
    message: 'Connected to backend server'
  }));

  // 处理接收到的消息
  ws.on('message', (message) => {
    try {
      const data = JSON.parse(message);
      console.log('Received message:', data);

      // 根据消息类型处理
      switch (data.type) {
        case 'getFoodToReplenish':
          handleGetFoodToReplenish(ws);
          break;
        case 'getFamilyMembersStatus':
          handleGetFamilyMembersStatus(ws);
          break;
        case 'getTomorrowWeather':
          handleGetTomorrowWeather(ws);
          break;
        case 'turnOnAirConditioner':
          handleTurnOnAirConditioner(ws, data.deviceCount);
          break;
        case 'getBowlsToWash':
          handleGetBowlsToWash(ws);
          break;
        default:
          ws.send(JSON.stringify({
            type: 'error',
            message: 'Unknown message type'
          }));
      }
    } catch (error) {
      console.error('Error processing message:', error);
      ws.send(JSON.stringify({
        type: 'error',
        message: 'Error processing message'
      }));
    }
  });

  // 处理连接关闭
  ws.on('close', () => {
    console.log('WebSocket connection closed');
  });
});

// 处理获取需要补充的食物
function handleGetFoodToReplenish(ws) {
  // 模拟数据 - 实际应用中应该从数据库和摄像头获取
  const foodTypes = [
    { id: 1, name: '苹果', alertQuantity: 5 },
    { id: 2, name: '香蕉', alertQuantity: 3 },
    { id: 3, name: '牛奶', alertQuantity: 2 },
    { id: 4, name: '面包', alertQuantity: 4 }
  ];

  // 模拟AI计算当前食物数量
  const currentQuantities = foodTypes.map(type => ({
    id: type.id,
    quantity: Math.floor(Math.random() * (type.alertQuantity + 5))
  }));

  // 确定需要补充的食物
  const foodToReplenish = foodTypes
    .map(type => ({
      ...type,
      currentQuantity: currentQuantities.find(cq => cq.id === type.id).quantity
    }))
    .filter(food => food.currentQuantity <= food.alertQuantity);

  // 发送响应
  ws.send(JSON.stringify({
    type: 'foodToReplenish',
    data: foodToReplenish
  }));
}

// 处理获取家庭成员状态
function handleGetFamilyMembersStatus(ws) {
  // 模拟数据
  const familyMembers = [
    { id: 1, name: '爸爸', status: '工作中' },
    { id: 2, name: '妈妈', status: '做饭中' },
    { id: 3, name: '儿子', status: '学习中' },
    { id: 4, name: '女儿', status: '玩耍中' }
  ];

  // 发送响应
  ws.send(JSON.stringify({
    type: 'familyMembersStatus',
    data: familyMembers
  }));
}

// 处理获取明天天气
function handleGetTomorrowWeather(ws) {
  // 模拟数据
  const weather = {
    temperature: `${Math.floor(Math.random() * 15) + 20}°C`,
    condition: ['晴朗', '多云', '小雨', '大雨'][Math.floor(Math.random() * 4)],
    wind: `${Math.floor(Math.random() * 5) + 1}级`
  };

  // 发送响应
  ws.send(JSON.stringify({
    type: 'tomorrowWeather',
    data: weather
  }));
}

// 处理开启空调
function handleTurnOnAirConditioner(ws, deviceCount) {
  // 模拟数据
  let result;
  if (deviceCount > 1) {
    // 模拟选择设备
    const selectedDevices = [1, 2].slice(0, Math.floor(Math.random() * deviceCount) + 1);
    result = {
      success: true,
      message: `已选择设备 ${selectedDevices.join(', ')} 并开启空调`
    };
  } else {
    result = {
      success: true,
      message: '已开启空调'
    };
  }

  // 发送响应
  ws.send(JSON.stringify({
    type: 'airConditionerStatus',
    data: result
  }));
}

// 处理获取需要洗的碗碟数量
function handleGetBowlsToWash(ws) {
  // 模拟数据 - 实际应用中应该从摄像头获取
  const bowlsCount = Math.floor(Math.random() * 10) + 1;

  // 发送响应
  ws.send(JSON.stringify({
    type: 'bowlsToWash',
    data: {
      count: bowlsCount
    }
  }));
}

// 启动服务器
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});